import router from './router'
import url from './url'
import Vue from 'vue'
import store from './store'
Vue.prototype.roles = url.roles
Vue.prototype.login = url.login
Vue.prototype.Eelec = url.Eelec
Vue.prototype.logout = url.logout

// ---------------------------------------------------------------------------------------
if (window.location.href.indexOf('ticket') == -1 && !sessionStorage.getItem('ticket')) {
  window.location.href = url.login + '/oauth?redirect_uri=' + encodeURIComponent(window.location.href.split('?')[0])
} else if (window.location.href.indexOf('ticket') != -1) {
  sessionStorage.setItem('ticket', window.location.href.split('?')[1].split('=')[1])
}
// ---------------------------------------------------------------------------------------
router.beforeEach((to, from, next) => {
  to.meta.title === undefined?document.title = 'loading':document.title = to.meta.title
  if (store.getters.roles && sessionStorage.getItem('custId')) {
    next()
  } else {
    store.commit('SET_ERRORTEXT', '获取账户信息')
    store.dispatch('GetUserInfo').then(res => {
      store.commit('SET_ERRORTEXT', '获取用户ID')
      store.dispatch('GetUser').then((res) => {
        store.commit('SET_ERRORTEXT', '获取能源类型')
        store.dispatch('GetCustMeterFlag').then((res) => {
          store.commit('SET_ERRORTEXT', '获取权限列表')
          store.dispatch('GetRoutes').then((res) => {
            store.dispatch('GenerateRoutes').then((res) => {
              store.commit('SET_ROLES')
              router.addRoutes(store.getters.addRouters)
              next({ ...to,
                replace: true
              })
            }).catch((err) => {})
          }).catch((err) => {})
        }).catch((err) => {})
      }).catch((err) => {})
    }).catch((err) => {})
  }
})